package com.liyu.iblog.service;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.google.appengine.api.datastore.Key;
import com.google.appengine.api.datastore.KeyFactory;
import com.liyu.iblog.dao.BlogDao;
import com.liyu.iblog.dao.CategoryDao;
import com.liyu.iblog.domain.Blog;
import com.liyu.iblog.domain.Category;
import com.liyu.iblog.utils.StringUtils;

@Service("categoryService")
public class CategoryServiceImpl implements CategoryService {

    private CategoryDao categoryDao;
    private BlogDao blogDao;
    
    @Autowired
    public CategoryServiceImpl(CategoryDao categoryDao, BlogDao blogDao) {
        this.categoryDao = categoryDao;
        this.blogDao = blogDao;
    }
    
    @Override
    public Category getCategory(Object key) {
        return categoryDao.get(key);
    }
    
    @Override
    public void saveCategory(Category category) {
        category.setId(StringUtils.transformToHyphenSeparatedString(category.getName()));
        Key key = KeyFactory.createKey(Category.class.getSimpleName(), category.getId());
        category.setKey(key);
        categoryDao.save(category);
    }
    
    @Override
    public void deleteCategory(String id) {
        Key ckey = KeyFactory.createKey(Category.class.getSimpleName(), id);
        Category category = categoryDao.get(ckey);
        if (category == null)
            return;
        
        //to remove a category, move all the blogs under this category to the defaultCategory
        if (category.getBlogKeys().size() > 0) {
            Category defaultCategory = categoryDao.get(CategoryService.DEFAULT_CATEGORY_NAME.toLowerCase());
            if (defaultCategory == null) {
                defaultCategory = new Category();
                defaultCategory.setName(CategoryService.DEFAULT_CATEGORY_NAME);
                defaultCategory.setId(CategoryService.DEFAULT_CATEGORY_NAME.toLowerCase());
                defaultCategory.setKey(KeyFactory.createKey(Category.class.getSimpleName(), defaultCategory.getId()));
            }
            Blog blog = null;
            for (Key bKey : category.getBlogKeys()) {
                blog = blogDao.get(bKey);
                if (blog == null)
                    continue;
                blog.setCategoryKey(defaultCategory.getId());
                defaultCategory.addBlogKey(blog.getKey());
                blogDao.save(blog);
            }
            categoryDao.save(defaultCategory);
        }
        categoryDao.delete(ckey);
    }
    
    @Override
    public List<Category> getAllCategories() {
        return categoryDao.getAll();
    }

}
